package com.olda.play.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import static com.olda.play.constant.Constant.INITIALIZE_PROMPT;

/**
 * https://gitee.com/nmwork/RedisUtil/#redisutil   RedisTemplate和StringRedisTemplate的区别
 * todo 灰常重要
 * https://www.csdn.net/tags/MtTaEgxsNTEyMDIwLWJsb2cO0O0O.html  在spring.factories 配置文件中开启自动配置
 */
@Configuration
public class RedisConfig {
    @Autowired
    private RedisConnectionFactory factory;
    private static final Logger logger = LoggerFactory.getLogger(RedisConfig.class);



    // 设置redis 的不同类型的序列化方式: 默认为Jackson：GenericJackson2JsonRedisSerializer
    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        template.setDefaultSerializer(new GenericJackson2JsonRedisSerializer());
        template.setKeySerializer(stringRedisSerializer);
        template.setHashKeySerializer(stringRedisSerializer);
        template.setConnectionFactory(factory);
        template.afterPropertiesSet();
        logger.info(String.format(INITIALIZE_PROMPT,"redis配置"));
        return template;
    }

    /**
     * 对redis字符串类型数据操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public ValueOperations<String, String> valueOperations(RedisTemplate<String, String> redisTemplate) {
        return redisTemplate.opsForValue();
    }
}